package com.lanxiao.cloud.modules.dict.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanxiao.cloud.common.core.enums.DelFlagEnum;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.common.mybatis.service.impl.BaseServiceImpl;
import com.lanxiao.cloud.modules.dict.domain.model.DictType;
import com.lanxiao.cloud.modules.dict.domain.service.IDictService;
import com.lanxiao.cloud.modules.dict.domain.service.IDictTypeService;
import com.lanxiao.cloud.modules.dict.infrastructure.error.DictErrorType;
import com.lanxiao.cloud.modules.dict.infrastructure.error.DictTypeErrorType;
import com.lanxiao.cloud.modules.dict.infrastructure.repository.DictTypeMapper;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2021-09-26
 */
@Service
public class DictTypeServiceImpl extends
    BaseServiceImpl<Long, DictTypeMapper, DictType> implements
    IDictTypeService {

  @Autowired
  private IDictService dictService;

  @Override
  public void saveDictType(DictType dictType) {
    BusinessException.isTrue(this.checkDictType(dictType.getType()),
        DictTypeErrorType.DICT_TYPE_TYPE_ERROR);
    this.save(dictType);
  }

  @Override
  public void updateDictType(DictType dictType) {
    BusinessException.isNonNull(this.getOne(new LambdaQueryWrapper<DictType>()
        .eq(DictType::getType, dictType.getType())
        .notLike(DictType:: getId, dictType.getId())), DictTypeErrorType.DICT_TYPE_TYPE_ERROR);
    this.updateById(dictType);
  }

  @Override
  public void delete(Long id) {
    DictType dictType = this.getById(id);
    if (Objects.nonNull(dictType)) {
      dictType.delete();
      this.updateById(dictType);
      dictService.deleteByType(dictType.getType());
    }
  }

  @Override
  public boolean checkDictType(String type) {
    return Objects.nonNull(
        this.getOne(
            new LambdaQueryWrapper<DictType>().eq(DictType::getType, type)
                .notLike(DictType::getDelFlag, DelFlagEnum.DELETE)
        )
    );
  }

}
